
import React from 'react'
import ReactDOM from 'react-dom'
import { DateField, Calendar } from 'react-date-picker'

class WorkStatus extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      data: {}
    }
  }

  componentWillReceiveProps(props) {
    this.setState({
      data: props.data
    })
  }

  componentDidUpdate() {
    // console.log(this.props.sysUser)
  }

  onChange(key, dateString) {
    var data = this.state.data
    data[key] = dateString
    this.setState({
      data: data
    })
  }

  onSubmitWorker() {

    var p_start = this.state.data.p_start,
        p_end = this.state.data.p_end


    var start, end
    if (p_start) {
      start = new Date(p_start)
    }

    if (p_end && p_end.length > 0) {
      end = new Date(p_end)
    }

    if (!start || !this.checkDate(start)) {
      alert("请选择预计开始时间!")
      return
    }

    if (end && this.checkDate(end)) {
      if (end.getTime() - start.getTime() < 0) {
        alert("选择的结束时间比开始时间早!")
        return
      }
    }

    // if (!end || !this.checkDate(end)) {
    //   alert("请选择预计结束时间!")
    //   return
    // }

    var priority = this.state.data.priority
    if (priority < 1 || priority > 4) {
      alert("请选择优先级!")
      return
    }

    var work_type = this.state.data.work_type
    if (work_type < 1 || work_type > 5) {
      alert("请选择类型!")
      return
    }

    this.props.onSubmitWorker({
      id: this.state.data.id,
      p_start: start,
      p_end: end,
      priority: this.state.data.priority,
      work_type: this.state.data.work_type,
      sys_user_id: this.props.sysUser.id,
      worker_name: this.state.data.worker_name || "",
      worker_phone: this.state.data.worker_phone || ""
    })

    this.setState({
      data: {
        p_start: p_start,
        p_end: p_end
      }
    })

    $(ReactDOM.findDOMNode(this.refs.workerName)).val(""),
    $(ReactDOM.findDOMNode(this.refs.workerPhone)).val("")
    // $(".react-date-field__input").val("")
  }

  onSubmitComplete() {
    if (confirm("确认关闭吗? 关闭后, 将无法修改!")) {
      this.props.onSubmitComplete({
        id: this.state.data.id
      })
    }
  }

  pad(n) {
    return n < 10 ? "0"+n : n;
  }


  checkDate(d) {
    if ( Object.prototype.toString.call(d) === "[object Date]" ) {
      // it is a date
      if ( isNaN( d.getTime() ) ) {  // d.valueOf() could also work
        // date is not valid
        return false
      }
      else {
        // date is valid
        return true
      }
    }
    else {
      // not a date
      return false
    }
  }

  renderWorker() {
    var data = this.props.data
    // console.log(data)
    var content = ""
    var sysUser = this.props.sysUser
    if (data && data.status != 'APPLYING' && sysUser && sysUser.WorkingProperty && !sysUser.WorkingProperty.isjde) {
      content = (
        <div>
          <div className="form-group">
            <label for="workUnit">维修人员</label>
            <input ref="workUnit" type="text" className="form-control"
                    id="workUnit" placeholder="维修人员" value={data.worker_name}
                    disabled/>
          </div>
          <div className="form-group">
            <label for="workUnit">维修人员电话</label>
            <input ref="workUnit" type="text" className="form-control"
                    id="workUnit" placeholder="维修人员电话" value={data.worker_phone}
                    disabled/>
          </div>
        </div>
      )
    }
    return content
  }

  renderSubmitWorker() {
    var data = this.props.data
    var content = ""
    var sysUser = this.props.sysUser
    if (sysUser && sysUser.WorkingProperty && !sysUser.WorkingProperty.isjde) {
      content = (
        <div>
          <div className="form-group">
            <label for="workUnit">维修人员</label>
            <input ref="workUnit" type="text" className="form-control"
                    id="workUnit" placeholder="维修人员" value={this.state.data.worker_name}
                    onChange={(event)=>this.onChange("worker_name", $(event.target).val())}
                    />
          </div>
          <div className="form-group">
            <label for="workUnit">维修人员电话</label>
            <input ref="workUnit" type="text" className="form-control"
                    id="workUnit" placeholder="维修人员电话" value={this.state.data.worker_phone}
                    onChange={(event)=>this.onChange("worker_phone", $(event.target).val())}
                    />
          </div>
        </div>
      )
    }
    return content
  }

  // 根据不同的状态, 显示不同的内容:
  //    未处理状态: 显示添加维修人员
  //    处理中: 显示"确认处理完毕"的按钮
  //    已处理待付款: 显示线下付款按钮
  //    已付款/已完成: 显示用户评价
  renderApplying() {
    var data = this.state.data
    var content = ""
    var now = new Date()
    var defaultDate = now.getFullYear()+""+(now.getMonth()+1)+"-"+now.getDate()
                      +" "+now.getHours()+":"+now.getMinutes()
    if (data) {
      if (data.status == 'APPLYING') {
        var priority
        if (data.priority == 4) {
          priority = "低"
        }else if (data.priority == 3) {
          priority = "中"
        }else if (data.priority == 2) {
          priority = "高"
        }else if (data.priority == 1) {
          priority = "紧急"
        }
        var work_type = ""
        switch(data.work_type){
          case 1:
            work_type = "房屋类故障";break;
          case 2:
            work_type = "给排类故障"; break;
          case 3:
            work_type = "空调类故障"; break;
          case 4:
            work_type = "强电类故障"; break;
          case 5:
            work_type = "弱点类故障"; break;
          default:
            break;
        }
        content = (
          <div className="panel panel-default">
            <div className="panel-body">
              <div className="form-group">
                <label for="workUnit">预计开始时间</label>
                <div className="">
                  <DateField
                    defaultDate={defaultDate}
                    locale='zh-cn'
                    dateFormat="YYYY-MM-DD HH:mm"
                    onChange={(dateString)=>this.onChange("p_start", dateString)}
                  />
                </div>
              </div>
              <div className="form-group">
                <label for="workUnit">预计结束时间</label>
                <div className="">
                  <DateField
                    defaultDate={defaultDate}
                    locale='zh-cn'
                    dateFormat="YYYY-MM-DD HH:mm"
                    onChange={(dateString)=>this.onChange("p_end", dateString)}
                  />
                </div>
              </div>
              <div className="form-group">
                <label for="workUnit">优先级</label>
                  <div>
                    <div className="btn-group">
                      <button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown">
                        <span className="caret"></span>
                        <span>{priority || "优先级"}</span>
                      </button>
                      <ul className="dropdown-menu" role="menu">
                        <li><a onClick={(event)=>this.onChange("priority", 1)}>紧急</a></li>
                        <li><a onClick={(event)=>this.onChange("priority", 2)}>高</a></li>
                        <li><a onClick={(event)=>this.onChange("priority", 3)}>中</a></li>
                        <li><a onClick={(event)=>this.onChange("priority", 4)}>低</a></li>
                      </ul>
                    </div>
                  </div>
              </div>
              <div className="form-group">
                <label for="workUnit">故障类型</label>
                  <div>
                    <div className="btn-group">
                      <button type="button" className="btn btn-default dropdown-toggle" data-toggle="dropdown">
                        <span className="caret"></span>
                        <span>{work_type || "类型"}</span>
                      </button>
                      <ul className="dropdown-menu" role="menu">
                        <li><a onClick={(event)=>this.onChange("work_type", 1)}>房屋类故障</a></li>
                        <li><a onClick={(event)=>this.onChange("work_type", 2)}>给排类故障</a></li>
                        <li><a onClick={(event)=>this.onChange("work_type", 3)}>空调类故障</a></li>
                        <li><a onClick={(event)=>this.onChange("work_type", 4)}>强电类故障</a></li>
                        <li><a onClick={(event)=>this.onChange("work_type", 5)}>弱点类故障</a></li>
                      </ul>
                    </div>
                  </div>
              </div>
              {this.renderSubmitWorker()}
              <div className="row">
                <button type="button" className="btn btn-primary col-sm-1 col-sm-offset-10"
                  onClick={(event)=>this.onSubmitWorker()}>提交</button>
              </div>
            </div>

          </div>
        )
      }
      else if (data.status == 'WORKING') {
        var completeClass = "btn btn-primary col-sm-2 "
        if (data.is_pay) {
          completeClass += "col-sm-offset-9"
        }else {
          completeClass += "col-sm-offset-1"
        }

        var payClass = "btn btn-primary col-sm-2 col-sm-offset-6 "
        const sysUser = this.props.sysUser
        if (sysUser.WorkingProperty && sysUser.WorkingProperty.isjde) {
          payClass = "btn btn-primary col-sm-2 col-sm-offset-9 "
          completeClass += " f-dn"
        }

        content = (
          <div className="row">
            {(data.is_pay || data.pay_type == 15)?null: <button type="button" className={payClass}
              onClick={(event)=>this.props.onPayOfflineClick()}>付款</button>}
            <button type="button" className={completeClass}
              onClick={(event)=>this.onSubmitComplete()}>确认关闭维修</button>
          </div>
        )

      }
      else if (data.status == 'COMPLETE' || data.status == 'FINISH') {
        var comment = "",
            remark = data.remark,
            date = ""
        if (data.kerry_work_order_comment && data.kerry_work_order_comment.length > 0) {
          comment = data.kerry_work_order_comment[0].content
        }
        if (data.sys_user) {
          remark = data.sys_user.firstName + data.sys_user.lastName + ": " + remark
        }
        if (data.pay_date) {
          var pay_date = new Date(data.pay_date)
          if (pay_date && pay_date != 'Invalid Date') {
            date = pay_date.getFullYear()+"年"+(pay_date.getMonth()+1)+"月"+(pay_date.getDate())+"日 "
                  + pay_date.getHours()+":"+pay_date.getMinutes()
          }
        }

        var completeClass = "btn btn-primary col-sm-2 "
        var syncClass = "btn btn-primary col-sm-2 "
        if (data.is_pay || data.pay_type == 15) {
          completeClass += " f-dn"
          if (data.is_push) {
            syncClass += " f-dn"
          }else {
            syncClass += " col-sm-offset-9"
          }
        }else {
          if (data.is_push) {
            syncClass += " f-dn"
            completeClass += " col-sm-offset-9"
          }else {
            syncClass += " col-sm-offset-1"
            completeClass += " col-sm-offset-6"
          }
        }
        // console.log(completeClass, syncClass)
        content = (
          <div>
            <div className="panel panel-default">
              <div className="panel-body">
                <div className="form-group">
                  <label for="workUnit">付款日期</label>
                  <input ref="workUnit" type="text" className="form-control"
                          id="workUnit" placeholder="付款日期" value={date}
                          disabled/>
                </div>
                <div className="form-group">
                  <label for="workUnit">付款备注</label>
                  <textarea ref="workUnit" type="text" className="form-control"
                          id="workUnit" placeholder="付款备注" value={remark}
                          disabled/>
                </div>
                <div className="form-group">
                  <label for="workUnit">用户评价</label>
                  <textarea ref="workUnit" type="text" className="form-control"
                          id="workUnit" placeholder="用户尚未评价" value={comment}
                          disabled/>
                </div>
              </div>
            </div>
            {
              <div className="row">
                <button type="button" className={completeClass}
                  onClick={(event)=>this.props.onPayOfflineClick()}>付款</button>
                <button type="button" className={syncClass}
                  onClick={(event)=>this.props.onWorkOrderSyncClick({id: data.id})}>同步至JDE</button>
              </div>
            }
          </div>
        )
      }
    }

    return content
  }

  render() {
    var self = this;
    var order_number, unit_desc, owner, mobile, gross_amount
    if (self.props.data) {
      order_number = self.props.data.jde_order_number || ""
      unit_desc = self.props.data.unit?self.props.data.unit.unit_desc:""
      owner = self.props.data.owner
      mobile = self.props.data.mobile
      gross_amount = parseFloat(self.props.data.gross_amount)
      if (!isNaN(gross_amount)) {
        gross_amount = gross_amount.toFixed(2)
      }else {
        gross_amount = ""
      }
    }

    return (
      <div className="modal fade work-detail" id="work-status" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div className="modal-dialog" role="document">
          <div className="modal-content">
            <div className="modal-header">
              <button type="button" className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 className="modal-title" id="WechatUser-modal-label">{"维修状态 "+order_number}</h4>
            </div>
            <div className="modal-body">
              <div className="panel panel-default">
                <div className="panel-body">
                  {
                    // <div className="form-group">
                    //   <label for="workUnit">户号</label>
                    //   <input ref="workUnit" type="text" className="form-control"
                    //           id="workUnit" placeholder="户号" value={unit_desc}
                    //           disabled/>
                    // </div>
                    // <div className="form-group">
                    //   <label for="workUnit">联系人</label>
                    //   <input ref="workUnit" type="text" className="form-control"
                    //           id="workUnit" placeholder="联系人" value={owner}
                    //           disabled/>
                    // </div>
                    // <div className="form-group">
                    //   <label for="workUnit">联系电话</label>
                    //   <input ref="workUnit" type="text" className="form-control"
                    //           id="workUnit" placeholder="联系电话" value={mobile}
                    //           disabled/>
                    // </div>
                  }
                  <div className="form-group">
                    <label for="workUnit">总费用(元)</label>
                    <input ref="workUnit" type="text" className="form-control"
                            id="workUnit" placeholder="总费用" value={gross_amount}
                            disabled/>
                  </div>
                  {self.renderWorker()}
                </div>
              </div>
              {self.renderApplying()}
            </div>
          </div>
        </div>
      </div>
    )
  }
}

export default WorkStatus
